const mongoose = require('mongoose');
//var connect=require('../mongodb')();

var deepPopulate = require('mongoose-deep-populate')(mongoose);
var Schema = mongoose.Schema;
//var topic=require('./topic');


var schema = new Schema({
    title:String,
    dec:String,
    text:String,
    source:String,//来源
    time:String,//时间
    img:String,//图片
    state:String,//状态
    hot:Boolean,
    commentnumber:{type:Number,default:1},//评论数
    praisenumber:{type:Number,default:1},//关注数
    amount:{type:Number,default:1},//浏览数
    userid:{type:mongoose.Schema.ObjectId,ref:'user'},
    tags:[{type:mongoose.Schema.ObjectId,ref:'tag'}],
    //话题 映射topic查询时用 populate
    topicid:{
        type:mongoose.Schema.ObjectId,
        'ref':'topic'
    },
    parentid:String,//主文章id
    
});
schema.plugin(deepPopulate,{
    populate:{
        'userid':{
            select:'name _id answernumber  contentnumber follownumber'
        }
    }
});

function _reject(err){
    return {errorCode:10,message:err.message}
}
function _resolve(data){
    return {
        errorCode:0,data:data
    }
}
//静态方法，用mode.来访问
function count (condition = {}){
    return new Promise((resolve, reject) => {
        this.count(condition).exec((err, data) => {
            if(err){
                reject(_reject(err))
            }else{
                resolve(_resolve(data))
            }
        })
    })
}
schema.statics._count=count;
schema.statics._findPage=function(condition = {}, {page = 1, limit = 10},populate,populatetwo,populatethree){
    return new Promise(async (resolve, reject) => {
        const totalResult = await this._count(condition);
        
        const skipFrom = page * limit - limit;
        this.find(condition).populate(populate).populate(populatetwo).populate(populatethree).skip(skipFrom).limit(limit).exec((err, data) => {
            if(err){
                reject(_reject(err))
            }else{
                resolve(_resolve({
                    list:data,
                    total:totalResult.data,
                    pageNo:page,
                    pageSize:limit
                }))
            }
            
        })
    })
}
//deeppopulate  ['userid']
schema.statics._findById=function(id,projection={},options={},deeppopulate){
    return new Promise((resolve,reject)=>{
        this.findById(id,projection,options)
        .deepPopulate(deeppopulate).exec((err,data)=>{
            if(err){
                reject(_reject(err))
            }else{
                resolve(_resolve(data))
            }
        })
    })
}

var model=mongoose.model('new',schema);
module.exports=model;

